import { SchemaManage } from '@/components/SchemaComponent';
import { ManageCommonAPI } from '@/pages/type';
import { useMemo, useRef, useState } from 'react';
import { connect } from 'umi';
import { PlusOutlined } from '@ant-design/icons';
import { deleteTempService, reviseTempService, saveToURLWordService, signTempService, templateManageService } from '../services';
import { getTableColumns, ntkoQueryParams } from '../mconfig';
import { UpdateViewModal } from './UpdateViewModal';
import { CancelModal } from '@/components/CancelModal';
import { ILoadMapTypeAll } from '@/common';
// import { DetailDrawer } from './DetailDrawer';
import { NtkoPlugin } from '@/common/NtkoPluginType';
import { getTenantID, wordToChildParams } from '@/utils';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';
import { message } from 'antd';
import { DetailDrawer } from './DetailDrawer';
import { getBaseUrl } from '@/services/urlconst';
import { SeeTemplateInfoModal } from './SeeTemplateInfoModal';

const TempContractManageView: React.FC<TempContractManageAPI.IManageType> = ({ curRes }) => {
  /** 管理页ref */
  const schemaManageRef: any = useRef();

  /** 申请页ref */
  const tipErrorModalRef: any = useRef();

  /**  获取管理页数据 */
  const { data, loading, pagination, searchList, getTempContractData, reloadRefresh } = templateManageService(curRes);

  /** 添加或编辑 */
  const [updataModalState, setUpdataModalState] = useState<Record<string, any>>({
    isShowModal: false,
    checkRowsInfo: {},
  });

  /** 点击按钮保存数据和弹框控制 */
  const [cancelModalState, setCancelModalState] = useState<Record<string, any>>({
    checkRowObj: {},
    showCancelModal: false,
  });

  /** 查看详情页面  */
  const [detailDrawerState, setDetailDrawerState] = useState<Record<string, any>>({
    isShowModal: false,
    checkRowsInfo: {},
  });

  /** 保存在线编辑权限 */
  const [saveNtkoQuery, setSaveNtkoQuery] = useState<Record<string, any>>({
    filedUrl: '',
    ntkoWordUrl: '',
  });

  /** 签发提示框 */
  const [openTipInfoModal, setOpenTipInfoModal] = useState<Record<string, any>>({
    checkRowObj: {},
    showModal: false,
    tipType: null, // sing :发布   delete:删除   amend:修订
  });

  /** 查看使用说明 */
  const [openSeeTempInfoStr, setOpenSeeTempInfoStr] = useState<Record<string, any>>({
    isShowModal: false,
    checkRowsInfo: {},
  });

  /**  重置搜索表单方法 */
  const onReset = (values: any) => {
    getTempContractData({ ...values });
  };

  /**  搜索列表 */
  const onSearch = (request: ManageCommonAPI.IGridRequestType) => {
    getTempContractData({ ...request });
  };

  /** 分页change 方法 */
  const onPageChange = (current: any, pageSize: any, params: any) => {
    getTempContractData({ pageSize, current, ...params });
  };

  /** 刷新管理页面 */
  const reloadManage = () => {
    reloadRefresh();
  };

  /** 保存文件接口回调 */
  const saveToUrlWordCallback = (res: any) => {
    const messageObj = {
      msgFlag: res?.msgFlag,
      msgText: res?.msg,
      msgType: 'uploadFiledRequest',
    };
    wordToChildParams(ntkoBrowser, saveNtkoQuery?.ntkoWordUrl, messageObj);
  };

  /** 保存文件接口 */
  const { wordSaveToURLRun } = saveToURLWordService(saveToUrlWordCallback);

  /** 保存文件回调 */
  const ntkoCallback = (childValue) => {
    const childBase = JSON.parse(childValue);
    if (childBase?.baseUrl && childBase?.baseObj) {
      const fieldUrl: string = childBase?.baseUrl?.split(getBaseUrl());
      wordSaveToURLRun({
        ...childBase,
        baseUrl: fieldUrl?.[1],
      });
    }
  };

  /** 引入在线预览 */
  const ntkoBrowser = useMemo(() => {
    const { ntkoBrowser } = NtkoPlugin(ntkoCallback);
    return ntkoBrowser;
  }, []);

  /** 打开在线预览文件 */
  const onOpenWord = (info: Record<string, any>) => {
    const { filedUrl, ntkoWordUrl } = ntkoQueryParams(info, curRes, 'templateURL');
    setSaveNtkoQuery({
      filedUrl,
      ntkoWordUrl,
    });
    const extensBool = ntkoBrowser.ExtensionInstalled();
    if (extensBool) {
      ntkoBrowser?.openWindow(ntkoWordUrl, false, '', '');
    }
  };

  /** 表格操作按钮点击方法 */
  const onOptClick: TempContractManageAPI.IOperationClick = {
    onView: (resObj) => {
      setDetailDrawerState({
        isShowModal: true,
        checkRowsInfo: resObj,
      });
    },
    onEdit: (resObj) => {
      setUpdataModalState({
        isShowModal: true,
        checkRowsInfo: resObj,
      });
    },
    onCancel: (resObj) => {
      setCancelModalState({
        checkRowObj: resObj,
        showCancelModal: true,
      });
    },
    onSign: (resObj) => {
      setOpenTipInfoModal({
        checkRowObj: resObj,
        showModal: true,
        tipType: 'sign',
      });
    },
    onNtko: (resObj) => {
      onOpenWord(resObj);
    },
    onDelete: (resObj) => {
      setOpenTipInfoModal({
        checkRowObj: resObj,
        showModal: true,
        tipType: 'delete',
      });
    },
    onAmend: (resObj) => {
      setOpenTipInfoModal({
        checkRowObj: resObj,
        showModal: true,
        tipType: 'amend',
      });
    },
    onSeeInfo: (resObj) => {
      setOpenSeeTempInfoStr({
        isShowModal: true,
        checkRowsInfo: resObj,
      });
    },
  };

  /** 获取columns方法 */
  const columns: Record<string, any>[] = useMemo(() => {
    return getTableColumns(curRes, onOptClick);
  }, [curRes]);

  /** 操作按钮列表 */
  const actionList: ManageCommonAPI.IActionList = useMemo(() => {
    return [
      {
        title: '添加',
        visible: curRes?.['/contractTemplateController/add'] || false,
        type: 'primary',
        icon: <PlusOutlined />,
        onClick: () => {
          setUpdataModalState({
            isShowModal: true,
            checkRowsInfo: {},
          });
        },
      },
    ];
  }, [curRes]);

  /** 签发按钮关闭 */
  const tipOnClose = () => {
    setOpenTipInfoModal({
      checkRowObj: {},
      showModal: false,
      tipType: null,
    });
  };

  /** 签发接口回调 */
  const signCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadManage();
      tipOnClose();
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入发布接口 */
  const { signTempRun } = signTempService(signCallback);

  /** 签发按钮 */
  const signModalOnOK = () => {
    const signPayload: Record<string, any> = {
      ...openTipInfoModal?.checkRowObj,
      id: openTipInfoModal?.checkRowObj?.id,
      state: `${getTenantID()}${ILoadMapTypeAll.CONTRACTTEMP_STATE}1002`,
      versionNum: openTipInfoModal?.checkRowObj?.versionNum,
    };
    signTempRun(signPayload);
  };

  /** 引入删除接口 */
  const { deleteTempRun } = deleteTempService(signCallback);

  /** 删除按钮 */
  const deleteModalOnOK = () => {
    const deletePayload: Record<string, any> = {
      id: openTipInfoModal?.checkRowObj?.id,
      versionNum: openTipInfoModal?.checkRowObj?.versionNum,
    };
    deleteTempRun(deletePayload);
  };

  /** 修订接口回调 */
  const reviseCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      onOpenWord(res?.obj);
      reloadManage();
      tipOnClose();
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入修订接口 */
  const { reviseTempRun } = reviseTempService(reviseCallback);

  /** 修订功能 */
  const reviseModalOnOk = () => {
    const revisePayload: Record<string, any> = {
      ...openTipInfoModal?.checkRowObj,
      state: `${getTenantID()}${ILoadMapTypeAll.CONTRACTTEMP_STATE}1001`,
    };
    reviseTempRun(revisePayload);
  };

  /** 返回提示框范本名称 */
  const renderTipName = (tipType: string) => {
    if (tipType == 'sign') {
      return (
        <div>
          确认是否发布【<span style={{ color: 'red' }}>{openTipInfoModal?.checkRowObj?.fullName || '--'}</span>】范本?
        </div>
      );
    } else if (tipType == 'delete') {
      return (
        <div>
          确认是否删除【<span style={{ color: 'red' }}>{openTipInfoModal?.checkRowObj?.fullName || '--'}</span>
          】范本，删除后不可恢复！
        </div>
      );
    } else if (tipType == 'amend') {
      return (
        <div>
          确认是否修订【<span style={{ color: 'red' }}>{openTipInfoModal?.checkRowObj?.fullName || '--'}</span>】范本？
        </div>
      );
    } else {
      return <></>;
    }
  };

  return (
    <div
      style={{
        position: 'relative',
        overflow: 'hidden',
        height: '100%',
        width: '100%',
      }}
    >
      <SchemaManage
        ref={schemaManageRef}
        searchProps={{
          switchList: [],
          searchList,
          onSwitch: () => {},
          onReset,
          onSearch,
        }}
        actionList={actionList}
        tableProps={{
          columns,
          dataSource: data?.rows,
          loading,
          pagination: pagination as any,
          rowKey: 'id',
          onPageChange, //分页onchange
        }}
      />

      {/* 签发提示框 */}
      {openTipInfoModal?.showModal && (
        <TipsErrorModalNew
          ref={tipErrorModalRef}
          modalLoading={false}
          onClose={tipOnClose}
          modalOnOK={
            openTipInfoModal?.tipType == 'sign'
              ? signModalOnOK
              : openTipInfoModal?.tipType == 'delete'
              ? deleteModalOnOK
              : openTipInfoModal?.tipType == 'amend'
              ? reviseModalOnOk
              : () => {}
          }
          tipTextColor="#000"
          modalTip={renderTipName(openTipInfoModal?.tipType)}
        />
      )}

      {/* 查看详情抽屉 */}
      <DetailDrawer
        curRes={curRes}
        onClose={() => {
          setDetailDrawerState({
            isShowModal: false,
            checkRowsInfo: {},
          });
        }}
        isShowDetail={detailDrawerState?.isShowModal}
        recordObj={detailDrawerState?.checkRowsInfo}
        reloadManage={reloadManage}
      />

      {/* 添加编辑弹框 */}
      {updataModalState?.isShowModal && (
        <UpdateViewModal
          onClose={() => {
            setUpdataModalState({
              isShowModal: false,
              checkRowsInfo: {},
            });
          }}
          checkRowsInfo={updataModalState?.checkRowsInfo}
          reloadManage={reloadManage}
          curRes={curRes}
        />
      )}

      {/* 查看使用说明 */}
      {openSeeTempInfoStr?.isShowModal && (
        <SeeTemplateInfoModal
          onClose={() => {
            setOpenSeeTempInfoStr({
              isShowModal: false,
              checkRowsInfo: {},
            });
          }}
          checkRowsInfo={openSeeTempInfoStr?.checkRowsInfo}
        />
      )}

      {/* 禁用提示框 */}
      {/* {applyModalInfo?.isShowModal && (
        <TipsErrorModalNew
          ref={tipErrorModalRef}
          modalLoading={false}
          onClose={() => {
            setApplyModalInfo({
              isShowModal: false,
              checkRowsInfo: {},
            });
          }}
          modalOnOK={() => {}}
          tipTextColor="#000"
          modalTip={
            <div>
              确认是否申请【<span style={{ color: 'red' }}>{applyModalInfo?.checkRowsInfo?.fullName || '--'}</span>】范本?
            </div>
          }
        />
      )} */}

      {/* 作废弹窗 */}
      {cancelModalState?.showCancelModal && (
        <CancelModal
          modalTitle="作废范本"
          modalWidth={0.25}
          cancelTypeDic={ILoadMapTypeAll.CONTRACTTEMP_CANCELTYPE}
          checkRows={cancelModalState?.checkRowObj}
          reloadManage={reloadManage}
          onClose={() => {
            setCancelModalState({
              checkRowObj: {},
              showCancelModal: false,
            });
          }}
          cancelFormReasonRequired={true}
          cancelRequestUrl={'/contractTemplateController/cancel'}
          cancelRequestBody={{
            ...cancelModalState?.checkRowObj,
            state: `${getTenantID()}${ILoadMapTypeAll.CONTRACTTEMP_STATE}1003`,
          }}
        />
      )}
    </div>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(TempContractManageView);
